import logging
from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager
from arq import ArqRedis
from fluentogram import TranslatorRunner

from src.presentation.tg_bot.states import IpChangePeriodSG

logger = logging.getLogger(__name__)


async def select_custom_period(call: types.CallbackQuery, widget: Any, manager: DialogManager):
    await manager.switch_to(IpChangePeriodSG.select_custom_period)


async def set_ip_change_period(
    call: types.CallbackQuery,
    widget: Any,
    manager: DialogManager,
    custom_period: str = None,
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")

    if custom_period:
        rotation_period = int(custom_period)
    else:
        rotation_period = int(widget.widget_id)

    if rotation_period == 0:
        reload_type = "by_link"
    else:
        reload_type = "by_time"

    arqredis: ArqRedis = manager.middleware_data.get("arqredis")

    order_id: int = manager.start_data.get("order_id")

    await arqredis.enqueue_job(
        "update_rotation_type",
        locale=locale,
        user_id=call.from_user.id,
        order_id=order_id,
        rotation_period=rotation_period,
        reload_type=reload_type,
    )

    logger.info(f"Добавлена задача по смене ротации заказа {order_id}")
    if isinstance(call, types.CallbackQuery):
        await call.message.answer(locale.get("in-work-msg"))
    else:
        await call.answer(locale.get("in-work-msg"))

    await manager.done()


async def start_rotation_period_change(message: types.Message, widget: Any, manager: DialogManager):
    if manager.start_data:
        order_id: int = manager.start_data.get("order_id")
    else:
        order_id: int = manager.dialog_data.get("order_id")

    await manager.start(IpChangePeriodSG.select_ip_change_period, {"order_id": order_id})
